package cn.mesmile.juc.demo;

import javax.lang.model.element.VariableElement;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zb
 * @date 2021/8/15 17:11
 * @Description
 */
public class AddAndSubLock {


    public static void main(String[] args) {
        CustomNumberLock customNumberLock = new CustomNumberLock();
        new Thread(() ->{
            for (int i = 0; i < 10 ; i++) {
                try {
                    customNumberLock.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(() ->{
            for (int i = 0; i < 10 ; i++) {
                try {
                    customNumberLock.desc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(() ->{
            for (int i = 0; i < 10 ; i++) {
                try {
                    customNumberLock.incr();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(() ->{
            for (int i = 0; i < 10 ; i++) {
                try {
                    customNumberLock.desc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }

}

/**
 * 创建资源类
 */
class CustomNumberLock {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    private  int number = 0;

    public void incr() throws InterruptedException {
        lock.lock();
        try {
            while (number > 0){
                // 等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"："+ number);
            // 通知
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void desc() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0){
                // 等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"："+ number);
            // 通知
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

}
